﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace RSSFeedReader.ViewModels
{
    /// <summary>
    /// A static class to provide common methods across the ViewModels.
    /// </summary>
    internal static class Common
    {
        /// <summary>
        /// Finds a <see cref="RSSFeedReader.ViewModels.ChannelViewModel"/> in the local collection based on the ID.
        /// </summary>
        /// <param name="id">
        /// The id to look for in the Collection of ChannelViewModel.
        /// </param>
        /// <param name="channelViewModelSource">The source of ChannelViewModels.</param>
        /// <returns>
        /// A <see cref="RSSFeedReader.ViewModels.ChannelViewModel"/> instance if found, null otherwise.
        /// </returns>
        internal static ChannelViewModel FindChannelViewModelById(Guid id, List<ChannelViewModel> channelViewModelSource)
        {
            return channelViewModelSource.Select(channelViewModel => FindChannelViewModelById(channelViewModel, id).FirstOrDefault()).FirstOrDefault(foundChannelVM => foundChannelVM != null);
        }

        /// <summary>
        /// Finds a <see cref="RSSFeedReader.ViewModels.ChannelViewModel"/> instance,
        /// whose ChannelViewModel.ID is equal to the ID passed in.
        /// </summary>
        /// <param name="channelViewModel">
        /// The <see cref="RSSFeedReader.ViewModels.ChannelViewModel"/> to test against
        /// the condition.
        /// </param>
        /// <param name="id">
        /// The ID to compare against.
        /// </param>
        /// <returns>
        /// A IEnumerable collection of type <see cref="RSSFeedReader.ViewModels.ChannelViewModel"/>.
        /// </returns>
       private static IEnumerable<ChannelViewModel> FindChannelViewModelById(ChannelViewModel channelViewModel,
            Guid id)
        {
            if (channelViewModel.ChannelID == id)
                yield return channelViewModel;

            foreach (ChannelViewModel child in channelViewModel.Children)
                foreach (ChannelViewModel isSameId in FindChannelViewModelById(child, id))
                    yield return isSameId;
        }
    }
}
